package com.weiqiao.mall.service.impl;

import com.google.gson.Gson;
import com.mingsoft.util.StringUtil;
import com.weiqiao.mall.domain.TeamEntity;
import com.weiqiao.mall.repository.IAppUserRepository;
import com.weiqiao.mall.repository.ITeamRepository;
import com.weiqiao.mall.service.ITeamService;
import com.weiqiao.mall.service.dto.TeamUserDTO;
import com.weiqiao.mall.service.vo.TeamVO;
import com.weiqiao.utils.DateUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("TeamServiceImpl")
public class TeamServiceImpl implements ITeamService {

    @Autowired
    private ITeamRepository team;

    @Autowired
    IAppUserRepository user;

    @Override
    public List<TeamEntity> teamList(TeamVO vo) {
        //Bson filter, Bson sort, int skip, int limit, int company_id
        Document doc = this.getFilter(vo);
        Document sort = new Document("create_date", -1); // 排序
        int pagesize = vo.getSize(); // 多少个
        int pagenum = vo.getPage() * pagesize; // 页数
        int company_id = vo.getCompany_id(); // 公司id
        List<String> list = team.teamList(doc, sort, pagenum, pagesize, company_id);
        List<TeamEntity> result = new ArrayList<>();
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        Gson gson = new Gson();
        list.forEach(s -> {
            TeamEntity teamEntity = gson.fromJson(s, TeamEntity.class);
            String time = teamEntity.getCreate_date();
            long create_time = Long.parseLong(time);
            teamEntity.setCreate_date(sd.format(new Date(create_time)));
            result.add(teamEntity);
        });
        return result;
    }

    @Override
    public List<String> teamList(Integer company_id, Document doc) {
        List<String> resultList = new ArrayList<>();
        List<String> list = team.getList(doc, company_id);
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(s -> resultList.add(new Gson().fromJson(s, TeamEntity.class).getTeam_id()));
        }
        return resultList;
    }

    private Document getFilter(TeamVO vo) {
        Document doc = new Document("delete_flag", 0); // 查询条件
        if (!StringUtils.isBlank(vo.getTeam_name())) {  //团队名称
            doc.append("team_name", new Document("$regex", vo.getTeam_name()));
        }
        if (!StringUtils.isBlank(vo.getLeader_name())) { //团队负责人
            doc.append("leader_name", new Document("$regex", vo.getLeader_name()));
        }
        if (!StringUtils.isBlank(vo.getPhone())) { //团队负责人联系电话
            doc.append("phone", new Document("$regex", vo.getPhone()));
        }
        if (vo.getCreate_id() > 0) {
            // 创建人大于0，根据创建人id，进行查询
            doc.append("create_id", vo.getCreate_id());
        }
        if (vo.getUser_id() > 0) {
            // 不是系统管理员查看，可能是团长、省长
            if (vo.getMember_type() == 3) {
                // 省长查看，查看自己创建的
                doc.append("create_id", vo.getUser_id());
            } else {
                // 团长查看自己团
                doc.append("team_id", vo.getTeam_id());
            }
        }
        int state = vo.getState();
        String status = state + "";
        if (!StringUtils.isBlank(status)) { //团队状态
            doc.append("state", vo.getState());
        }
        return doc;
    }

    @Override
    public TeamEntity getTeamInfo(int companyId, String team_id) {
        String info = team.findOne(companyId, new Document("team_id", team_id));
        if (StringUtil.isBlank(info)) return new TeamEntity();
        return new Gson().fromJson(info, TeamEntity.class);
    }

    @Override
    public Map<String, Object> updateTeam(TeamVO vo) {
        Document bson = new Document(); //条件
        Document doc = new Document(); // 内容
        Map<String, Object> map = new HashedMap();
        if (StringUtils.isBlank(vo.getTeam_id())) {
            map.put("result", false);
            map.put("resultmsg", "团队Id不能为空");
            return map;
        }
        bson.append("team_id", vo.getTeam_id());
        int company_id = vo.getCompany_id();
        String time = DateUtils.currentTimeMillis();
        doc.append("update_date", time);
        doc.append("team_name", vo.getTeam_name());
        doc.append("leader_id", vo.getLeader_id());
        doc.append("leader_name", vo.getLeader_name());
        doc.append("phone", vo.getPhone());
        doc.append("remark", vo.getRemark());
        doc.append("state", vo.getState());
        team.updateTeam(bson, doc, company_id);
        if (vo.getLeader_id() > 0) {
            // 释放当前团队，团队负责人
            Document releaseFilter = new Document("team_id", vo.getTeam_id()).append("active_team", 1);
            user.updateAppUser(new Document("active_team", 0), releaseFilter, company_id);
            // 为团队新增新的团队负责人
            Document filter_user = new Document("user_id", vo.getLeader_id());
            Document doc_team = new Document();
            doc_team.append("active_team", 1);
            doc_team.append("team_id", vo.getTeam_id());
            doc_team.append("team_name", vo.getTeam_name());
            user.updateAppUser(doc_team, filter_user, company_id);
        }
        map.put("result", true);
        map.put("resultmsg", "修改成功");
        return map;
    }

    @Override
    public Map<String, Object> insertTeam(TeamVO vo) {
        int company_id = vo.getCompany_id();
        Map<String, Object> map = new HashedMap();
        String time = DateUtils.currentTimeMillis();
        vo.setCreate_date(time);
        vo.setTeam_id(time);
        String json = new Gson().toJson(vo);
        team.insertTeam(json, company_id);
        // 若负责人id不为空，还需要把用户指定为团队负责人
        if (vo.getLeader_id() > 0) {
            Document filter = new Document("user_id", vo.getLeader_id());
            Document doc = new Document();
            doc.append("team_id", time);
            doc.append("active_team", 1);
            doc.append("team_name", vo.getTeam_name());
            user.updateAppUser(doc, filter, company_id);
        }
        map.put("result", true);
        map.put("resultmsg", "添加成功");
        return map;
    }

    @Override
    public Map<String, Object> deleteTeam(TeamVO vo) {
        int company_id = vo.getCompany_id();
        Map<String, Object> map = new HashedMap();
        Document filter = new Document();
        Document doc = new Document();
        if (StringUtils.isBlank(vo.getTeam_id())) {
            map.put("result", false);
            map.put("resultmsg", "团队Id不能为空");
            return map;
        }
        filter.append("team_id", vo.getTeam_id());
        doc.append("delete_flag", 1);
        Boolean lean = team.deleteTeam(filter, doc, company_id);
        Document doc_team = new Document();
        doc_team.append("active_team", 0);
        doc_team.append("team_id", "");
        doc_team.append("team_name", "");
        Boolean userTeam = user.updateAppUser(doc_team, filter, company_id);
        if (lean && userTeam) {
            map.put("result", true);
            map.put("resultmsg", "删除成功");
        } else {
            map.put("result", false);
            map.put("resultmsg", "删除失败");
        }
        return map;
    }

    @Override
    public int countTeam(TeamVO vo) {
        Document doc = this.getFilter(vo);
        int company_id = vo.getCompany_id();
        return team.countTeam(company_id, doc);
    }

    @Override
    public List<TeamUserDTO> notLeaderList(TeamVO vo) {
        Document doc = new Document();
        int company_id = vo.getCompany_id();
        doc.append("active_team", 0); //不带团
        doc.append("member_type", 2); //是团长
        List<String> list = user.getAppUserListByUserId(doc, company_id);
        List<TeamUserDTO> result = new ArrayList<>();
        Gson gson = new Gson();
        list.forEach(s -> {
            TeamUserDTO teamEntity = gson.fromJson(s, TeamUserDTO.class);
            result.add(teamEntity);
        });
        return result;
    }
}
